<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/11
 * Time: 13:18
 */

namespace app\index\controller;
use QcloudImage\CIClient;

class Sample
{
    public function sign(){
        $appid = "1257429156";
        $bucket = "";
        $secret_id = "AKID5EC3jQ7ocIm5FEbfrz4vb6QbbYKw9gv3";
        $secret_key = "W0R0S7i9OKj18496sX3QcgZzsdN0a6Qa";
        $expired = time() + 2592000;
        $onceExpired = 0;
        $current = time();
        $rdm = rand();
        $userid = "0";
        $fileid = "tencentyunSignTest";

        $srcStr = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm.'&f=';

        $srcWithFile = 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$expired.'&t='.$current.'&r='.$rdm.'&f='.$fileid;

        $srcStrOnce= 'a='.$appid.'&b='.$bucket.'&k='.$secret_id.'&e='.$onceExpired .'&t='.$current.'&r='.$rdm
            .'&f='.$fileid;
        $signStr = base64_encode(hash_hmac('SHA1', $srcStr, $secret_key, true).$srcStr);

        $srcWithFile = base64_encode(hash_hmac('SHA1', $srcWithFile , $secret_key, true).$srcWithFile );

        $signStrOnce = base64_encode(hash_hmac('SHA1',$srcStrOnce,$secret_key, true).$srcStrOnce);
        return ['code' =>200,'message'=> '签名信息','signStr' =>$srcStr,'srcWithFile' => $srcWithFile,'signStrOnce'=> $signStrOnce];
        echo $signStr."\n";

        echo $srcWithFile ."\n";

        echo $signStrOnce."\n";
    }

    public function upload(){
        //require_once __DIR__ . '/index.php';
        $file = request()->file('image');
        require_once '../extend/image-php-sdk-v2.0-master/index.php';
        $appid = '1257429156';
        $secretId = 'AKID5EC3jQ7ocIm5FEbfrz4vb6QbbYKw9gv3';
        $secretKey = 'W0R0S7i9OKj18496sX3QcgZzsdN0a6Qa';
        $bucket = '';

        $client = new CIClient($appid, $secretId, $secretKey, $bucket);

//推荐使用https
        $client->useHttps();

// 设置超时
        $client->setTimeout(30);

// 选择服务器域名, 推荐使用新域名 useNewDomain ( recognition.image.myqcloud.com )
//
// 如果你:
//      1.正在使用人脸识别系列功能( https://cloud.tencent.com/product/FaceRecognition/developer )
//      2.并且是通过旧域名访问的
// 那么: 请继续使用旧域名
        $client->useNewDomain();

//根据你的网络环境, 可能需要设置代理
//$client->setProxy('127.0.0.1:12759');
        //行驶证驾驶证识别
//单个或多个图片file
        var_dump ($client->drivingLicence(array('file'=>'http://lihai.xmdonkey.com/aaa.jpg'),1/*0表示行驶证，1表示驾驶证*/));
//使用buffer
//        var_dump ($client->drivingLicence(array('buffer'=>file_get_contents('/aaa.jpg')),1/*0表示行驶证，1表示驾驶证*/));
////单个或多个图片Url
//        var_dump ($client->drivingLicence(array('url'=>'IMAGE_URL'), 1/*0表示行驶证，1表示驾驶证*/));
    }

    public function kd(){
        $url = "https://dm-53.data.aliyun.com/rest/160601/ocr/ocr_vehicle.json";
        $appcode = "8ac4b41d14ed415495c9662bbdaff312";
        //$file = "./111.jpg";
        $protecter_face = uploadOne('image');
        $file = $protecter_face;
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        $config = array(
            "side" => "face"
        );
        //$config = array()


        if($fp = fopen($file, "rb", 0)) {
            $binary = fread($fp, filesize($file)); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        if($is_old_format == TRUE){
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );

            if(count($config) > 0){
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        }else{
            $request = array(
                "image" => "$base64"
            );
            if(count($config) > 0){
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$url, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);

        $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        if($httpCode == 200){
            $output = json_decode($rbody, true);
            if($is_old_format){

                $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
            }else{

                //$result_str = $rbody;
                $output['config_str'] = \GuzzleHttp\json_decode($output['config_str'],true);
                $result_str = $output;
            }

            $result_str['issue_date'] = $this->date($result_str['issue_date']);
            $result_str['register_date'] = $this->date($result_str['register_date']);
            return ['code'=>200,'message' => '行驶证信息','data' => $result_str];
            printf("result is :\n %s\n", $result_str);
        }else{
            printf("Http error code: %d\n", $httpCode);
            printf("Error msg in body: %s\n", $rbody);
            printf("header: %s\n", $rheader);
        }
    }

    protected function date($variable)
    {
        $year  = mb_substr($variable, 0, 4);
        $month = mb_substr($variable, 4, 2);
        $day   = mb_substr($variable, 6, 2);

        $date_create = date_create($year . '-' . $month . '-' . $day);

        $date = date_format($date_create, 'Y-m-d H:i:s');
        return $date;
    }
}